package com.ruoyi.yl.common.yl_enum;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: 项目类别
 */
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
@Getter
@AllArgsConstructor
public enum UnitType {


    /**
     * 次
     */
    COMMON_TIME(0, "次"),

    /**
     * 项
     */
    COMMON_ITEM(1, "项"),

    /**
     * 盒
     */
    COMMON_BOX(2, "盒"),

    /**
     * 支
     */
    COMMON_COUNT(3, "支");


    private final Integer value;
    private final String description;

    /**
     * 用于保存所有的枚举值
     */
    private static Map<String, UnitType> RESOURCE_MAP = Stream
            .of(UnitType.values())
            .collect(Collectors.toMap(s -> s.getDescription(), Function.identity()));

    /**
     * 枚举反序列话调用该方法
     * @param jsonNode
     * @return
     */
    @JsonCreator
    public static UnitType des(final JsonNode jsonNode) {
        return Optional
                .ofNullable(RESOURCE_MAP.get(jsonNode.get("description").asText()))
                .orElseThrow(() -> new IllegalArgumentException(jsonNode.get("description").asText()));
    }


    public static UnitType getEnum(Integer value) {
        for (UnitType prescriptionType : UnitType.values()) {
            if (prescriptionType.getValue().equals(value)) {
                return prescriptionType;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        return String.valueOf(this.value);
    }

}
